package com.easpeed.comon.utils

import android.content.Context
import android.graphics.drawable.GradientDrawable
import android.graphics.drawable.StateListDrawable
import androidx.annotation.ColorInt
import androidx.annotation.Dimension

object SelectorUtils {

    /**
     * 创建一个 StateListDrawable
     * @param context Context 上下文
     * @param normalColor 未激活状态颜色
     * @param activatedColor 激活状态颜色
     * @param cornerRadius 圆角半径（dp）
     * @return StateListDrawable 对象
     */
    fun createSelector(
        context: Context,
        @ColorInt normalColor: Int,
        @ColorInt activatedColor: Int,
        @Dimension cornerRadius: Float,
    ): StateListDrawable {
        val stateListDrawable = StateListDrawable()

        // 创建未激活状态的 Drawable
        val normalDrawable = GradientDrawable().apply {
            shape = GradientDrawable.RECTANGLE
            setColor(normalColor)
            this.cornerRadius = dpToPx(context, cornerRadius)
        }

        // 创建激活状态的 Drawable
        val activatedDrawable = GradientDrawable().apply {
            shape = GradientDrawable.RECTANGLE
            setColor(activatedColor)
            this.cornerRadius = dpToPx(context, cornerRadius)
        }

        // 添加状态到 StateListDrawable
        stateListDrawable.addState(intArrayOf(android.R.attr.state_activated), activatedDrawable)
        stateListDrawable.addState(intArrayOf(-android.R.attr.state_activated), normalDrawable)

        return stateListDrawable
    }

    /**
     * dp 转 px
     */
    private fun dpToPx(context: Context, dp: Float): Float {
        return dp * context.resources.displayMetrics.density
    }
}